﻿<%@ WebHandler Language="C#" Class="filedownload" %>

using System;
using System.Web;
using System.IO;
using System.Text;
using EasyFMS.Common;
using Liger.Data;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

public class filedownload : IHttpHandler
{
    public static DbContext DB = DbHelper.Db;

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Clear();
        FileDownLoad(context);
        context.Response.Flush();
        context.Response.End();
    }

    public void FileDownLoad(HttpContext context)
    {
        SqlCommand myCmd = new SqlCommand("SELECT DocName,Doc FROM dbo.cInstead WHERE IsDoc = 1 AND UID  = " + context.Request["uid"].ToString(), new SqlConnection(DB.Db.ConnectionString));
        if (myCmd.Connection.State == ConnectionState.Closed)
            myCmd.Connection.Open();
        SqlDataReader myReader = myCmd.ExecuteReader();
        try
        {
            if (myReader.Read())
            {
                context.Response.Clear();
                context.Response.Buffer = true;
                context.Response.Charset = "utf-8";
                context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(context.Request.ContentEncoding.GetBytes(myReader["DocName"].ToString())));
                context.Response.AddHeader("Content-Transfer-Encoding", "binary");
                context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                context.Response.BinaryWrite((byte[])myReader["Doc"]);
            }
            else
            {
                context.Response.Write("ER||没有附件可下载"); 
            }
        }
        catch (Exception ex) { context.Response.Write(ex.Message.ToString()); }
        finally
        {
            myReader.Close();
            myReader.Dispose();
            myCmd.Dispose();
            myCmd.Connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}